//
//  HJPostInformationController.m
//  KaiChat
//
//  Created by lx on 2024/3/12.
//

#import "HJPostInformationController.h"
#import "HJNavigationController.h"
#import "HMSegmentedControl.h"
#import "HJInformationPresent.h"
#import "QMUITextView.h"
#import "QMUITextField.h"
#import "HJPostInformationSelectImageCell.h"
#import "HJSelectFile.h"
#import "HJSelectMediaController.h"
#import "TZImageManager.h"
#import "HJNetworkReachabilityManager.h"

@interface HJPostInformationController ()<QMUITextFieldDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, assign) NSInteger maxLenght;
@property (nonatomic, weak) HJBarButton *doneButton;
@property (nonatomic, weak) UIView *postView;
@property (nonatomic, weak) UIView *longView;
@property (nonatomic, weak) QMUITextView *longTextView;
@property (nonatomic, weak) QMUITextView *postTextView;
@property (nonatomic, weak) UILabel *lengthLabel;
@property (nonatomic, strong) NSMutableArray *selectModels;
@property (nonatomic, strong) HJSelectFile *selectFile;
@property (nonatomic, strong) HJSelectImageModel *addImageModel;
@property (nonatomic, weak) HMSegmentedControl *segmentedControl;
@property (nonatomic, weak) QMUITextField *titleTextField;
@property (nonatomic, assign) BOOL isSelectVideo;
@property (nonatomic, assign) NSInteger selectImageMaxCount;
@property (nonatomic, assign) NSInteger selectVideoMaxCount;

@end

@implementation HJPostInformationController


+ (void)showInController:(UIViewController *)controller {
    HJPostInformationController *postInformationController = [[HJPostInformationController alloc] init];
    HJNavigationController *navigationController = [[HJNavigationController alloc] initWithRootViewController:postInformationController];
    [controller presentViewController:navigationController animated:YES completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"Issue";
    
    self.maxLenght = 600;
    self.selectImageMaxCount = 9;
    self.selectVideoMaxCount = 1;
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    HJBarButton *doneButton = [HJBarButton barButtonWithTitle:@"Done" color:UIColor.tj_mainColor target:self action:@selector(didClickDoneButton)];
    [doneButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    doneButton.enabled = NO;
    [self.navigationBar.contentView addSubview:doneButton];
    [doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.width.offset(40);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    _doneButton = doneButton;
    
    UIView *segmentedView = [UIView addToView:self.view];
    [segmentedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight);
        make.left.right.offset(0);
        make.height.offset(50);
    }];
    
    UIView *lineView = [UIView addToView:segmentedView];
    lineView.backgroundColor = UIColor.tj_separatorColor;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(0);
        make.height.offset(0.7);
        make.bottom.offset(0);
    }];
    
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Post", @"Long text"]];
    segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
    segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationBottom;
    segmentedControl.selectionIndicatorHeight = 1;
    segmentedControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    segmentedControl.selectionIndicatorColor = UIColor.tj_333333Color;
    segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
    segmentedControl.verticalDividerEnabled = NO;
    segmentedControl.backgroundColor = UIColor.clearColor;
    [segmentedControl setTitleTextAttributes:@{
        NSForegroundColorAttributeName : UIColor.tj_BEBDCAColor,
        NSFontAttributeName : UIFontMake(16)
    }];
    [segmentedControl setSelectedTitleTextAttributes:@{
        NSForegroundColorAttributeName : UIColor.tj_333333Color,
        NSFontAttributeName : UIFontMediumMake(16)
    }];
    [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [segmentedView addSubview:segmentedControl];
    [segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(10);
        make.bottom.offset(0);
        make.height.offset(50);
    }];
    
    UIView *postView = [self addPostView].addTo(self.view);
    [postView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(segmentedView.mas_bottom);
        make.height.offset(160);
    }];
    
    UIView *longView = [self addLongView].addTo(self.view);
    longView.hidden = YES;
    [longView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(segmentedView.mas_bottom);
        make.height.offset(160);
    }];
    
    UILabel *lengthLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:@"100/4000" textAlignment:NSTextAlignmentLeft];
    [lengthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(leftRightMargin);
        make.top.equalTo(segmentedView.mas_bottom).inset(160);
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(lengthLabel.mas_bottom).offset(20);
        make.height.offset(HZoom(113));
    }];
    
    _lengthLabel = lengthLabel;
    _postView = postView;
    _longView = longView;
    _segmentedControl = segmentedControl;
    
    [self updataLengthLabel];
    
    _addImageModel = [HJSelectImageModel modelWithBlock:^(HJSelectImageModel * _Nonnull model) {
        model.isAdd = YES;
        model.image = [UIImage imageNamed:@"selectImage_add"];
    }];
    
    [self.selectModels addObject:_addImageModel];
}

- (UIView *)addPostView {
    UIView *postView = [[UIView alloc] init];
    
    QMUITextView *postTextView = [QMUITextView addToView:postView];
    postTextView.font = UIFontMake(14);
    postTextView.tintColor = UIColor.tj_mainColor;
    postTextView.placeholderColor = UIColor.tj_placeholderTextColor;
    postTextView.placeholder = @"Say something...";
    postTextView.maximumTextLength = 600;
    [postTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin - 6);
        make.top.offset(0);
        make.bottom.inset(0);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextChanged:) name:UITextViewTextDidChangeNotification object:postTextView];
    
    _postTextView = postTextView;
    return postView;
}

- (UIView *)addLongView {
    
    UIView *longView = [[UIView alloc] init];
    
    UIView *titleView = [UIView addToView:longView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(50);
    }];
    
    QMUITextField *textField = [QMUITextField addToView:titleView];
    textField.font = UIFontMediumMake(14);
    textField.delegate = self;
    textField.placeholder = @"Headline";
    textField.tintColor = UIColor.tj_cursorColor;
    textField.returnKeyType = UIReturnKeyDone;
    textField.textColor = UIColor.tj_1A1A1AColor;
    textField.maximumTextLength = 300;
    textField.placeholderColor = UIColor.tj_placeholderTextColor;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.bottom.offset(0);
    }];
    
    UIView *titleLineView = [UIView addToView:titleView];
    titleLineView.backgroundColor = UIColor.tj_separatorColor;
    [titleLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.height.offset(0.7);
        make.bottom.offset(0);
    }];
    
    QMUITextView *longTextView = [QMUITextView addToView:longView];
    longTextView.font = UIFontMake(14);
    longTextView.tintColor = UIColor.tj_mainColor;
    longTextView.placeholderColor = UIColor.tj_placeholderTextColor;
    longTextView.placeholder = @"Text";
    [longTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin - 6);
        make.top.equalTo(titleView.mas_bottom);
        make.bottom.inset(0);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextChanged:) name:UITextViewTextDidChangeNotification object:longTextView];
    
    _titleTextField = textField;
    _longTextView = longTextView;
    return longView;
}

- (void)handleTextChanged:(NSNotification *)not {
    if (not.object == _longTextView) {
        self.doneButton.enabled = !isEmptyString(_longTextView.text) || [self isSelectMedia];
    } else if (not.object == _postTextView) {
        self.doneButton.enabled = !isEmptyString(_postTextView.text) || [self isSelectMedia];;
        [self updataLengthLabel];
    }
    
}

- (BOOL)isSelectMedia {
    if (self.selectModels.count == 1 && self.selectModels.firstObject == self.addImageModel) {
        return NO;
    }
    return YES;
}

- (void)updataLengthLabel {
    if (_segmentedControl.selectedSegmentIndex > 0) {
        _lengthLabel.hidden = YES;
 
    } else {
        _lengthLabel.hidden = NO;
        if ( _postTextView.text.length > 0) {
            _lengthLabel.attributedText = [[NSString stringWithFormat:@"%ld/%ld", _postTextView.text.length, _maxLenght] attributedStringWithRangeString:[NSString stringWithFormat:@"%ld", _postTextView.text.length] rangeColor:UIColor.tj_333333Color color:UIColor.tj_BEBDCAColor];
        } else {
            _lengthLabel.attributedText = [[NSString stringWithFormat:@"%ld/%ld", _postTextView.text.length, _maxLenght] attributedStringWithRangeString:[NSString stringWithFormat:@"%ld", _postTextView.text.length] rangeColor:UIColor.tj_BEBDCAColor color:UIColor.tj_BEBDCAColor];
        }
    }
    
}

- (void)didClickDoneButton {
    
    [self.view endEditing:YES];
    
    if (!HJNetworkReachabilityManager.shareManager.reachable) {
        [HJHUD showErrorMessage:@"Network error, sending failure"];
        return;
    }
    
    [HJHUD showLoadingInView:self.view];
    
    if (![self isSelectMedia]) {
        [self uploadImageComplete];
        return;
    }

    if ([self isSelectVideo]) {
        
        HJSelectImageModel *model = self.selectModels.firstObject;
        PHAsset * phAsset = model.asset;
        
        [[TZImageManager manager] requestVideoURLWithAsset:phAsset success:^(NSURL *videoURL) {
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                NSString *filePath = [NSString stringWithFormat:@"%@.%@", phAsset.localIdentifier, videoURL.lastPathComponent.pathExtension].tj_tmpCachePath;
                if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                }
                
                NSError *error = nil;
                [[NSFileManager defaultManager] copyItemAtURL:videoURL toURL:[NSURL fileURLWithPath:filePath] error:&error];
                
                if (!error) {
                    
                    TJLog(@"写入视频成功 = %@", filePath);

                    NSString *objectKey = getUploadFileKey(HJFileTypeVideo, [NSString stringWithFormat:@"%@.%@", [NSString stringWithFormat:@"%.f", NSDate.date.timeIntervalSince1970 * 1000].md5, videoURL.lastPathComponent.pathExtension]);
                    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    
                    [HJNetworking.shareNetwork uploadImageWithObejctKey:objectKey fileData:fileData progress:nil success:^(NSString * _Nonnull url) {
                        model.url = url;
                        [self uploadImageComplete];
                    } failure:^(NSError * _Nonnull error) {
                 
                    }];
                } else {
                    TJLog(@"写入视频error = %@ \n filePath = %@", error, filePath);
                }
            });
        } failure:^(NSDictionary *info) {
 
        }];
    } else {
        
        dispatch_async_queue(^{
            
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
            for (int i = 0; i < self.selectModels.count; i++) {
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                
                HJSelectImageModel *model = self.selectModels[i];
                
                NSString *objectKey = getUploadFileKey(HJFileTypeImage, [NSString stringWithFormat:@"%@.%@", [NSString stringWithFormat:@"%.f", NSDate.date.timeIntervalSince1970 * 1000].md5, @"jpg"]);
                NSData *fileData = UIImageJPEGRepresentation(model.image, 0.7);
                
                [HJNetworking.shareNetwork uploadImageWithObejctKey:objectKey fileData:fileData progress:nil success:^(NSString * _Nonnull url) {
                    model.url = url;
                    dispatch_semaphore_signal(semaphore);
                    if (i == self.selectModels.count - 1) {
                        [self uploadImageComplete];
                    }
                } failure:^(NSError * _Nonnull error) {
                    dispatch_semaphore_signal(semaphore);

                    if (i == self.selectModels.count - 1) {
                        [self uploadImageComplete];
                    }
                }];
            }
        });
  
    }
}

- (void)uploadImageComplete {
    
    NSString *title = nil;
    NSString *content = nil;
    
    if (self.segmentedControl.selectedSegmentIndex == 1) {
        title = self.titleTextField.text;
        content = self.longTextView.text;
    } else {
        content = self.postTextView.text;
    }
    
    NSMutableArray *images = nil;
    NSMutableArray *videos = nil;
    
    if ([self isSelectMedia]) {
  
        if ([self isSelectVideo]) {
            videos = [NSMutableArray array];
            for (HJSelectImageModel *model in self.selectModels) {
                if (!model.isAdd) {
                    if (model.url) {
                        [videos addObject:model.url];
                    }
                }
            }
        } else {
            images = [NSMutableArray array];
            for (HJSelectImageModel *model in self.selectModels) {
                if (!model.isAdd) {
                    if (model.url) {
                        [images addObject:model.url];
                    }
                }
            }
        }
    }
    
    if (isEmptyString(title) && isEmptyString(content) && images.count == 0 && videos.count == 0) {
        [HJHUD showErrorMessage:@"Send failed, please send again!"];
        return;
    }

    [HJInformationPresent postNewsWithTitle:title content:content images:images videos:videos complete:^(NSError * _Nullable error) {
        if (error) {
            return;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:postNewsSucceedNotification object:nil];
        [HJHUD showSucceedMessageTip];
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}


- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    if (segmentedControl.selectedSegmentIndex == 0) {
        self.postView.hidden = NO;
        self.longView.hidden = YES;
        _maxLenght = 600;
    } else {
        self.postView.hidden = YES;
        self.longView.hidden = NO;
        _maxLenght = 600;
    }
    [self updataLengthLabel];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.selectModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HJPostInformationSelectImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HJPostInformationSelectImageCell" forIndexPath:indexPath];
    cell.model = self.selectModels[indexPath.row];
    TJWeakify(self)
    [cell setDidClickDeleteButtonBlock:^(HJSelectImageModel *  _Nonnull deleteModel) {
                
        NSInteger maxCount = deleteModel.asset ? weakself.selectVideoMaxCount : weakself.selectImageMaxCount;
        [weakself.selectModels removeObject:deleteModel];
        
        if (![weakself.selectModels containsObject:weakself.addImageModel] && weakself.selectModels.count < maxCount) {
            [weakself.selectModels addObject:weakself.addImageModel];
            [weakself.collectionView reloadData];
        } else {
            [weakself.collectionView deleteItemsAtIndexPaths:@[indexPath]];
            
        }
    }];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HJSelectImageModel *model = self.selectModels[indexPath.row];
    if (model.isAdd) {
        
        HJSelectMediaController *selectMediaController = [[HJSelectMediaController alloc] init];
        [selectMediaController setComplete:^(HJCellModel * _Nonnull cellModel) {
            if ([cellModel.anyObject intValue] == 1) {//photo
                [self selectImage];
            } else {
                [self selectVideo];
            }
        }];
        
        [self presentViewController:selectMediaController animated:NO completion:nil];
        return;
    }
    
}

- (void)selectImage {
    
    self.isSelectVideo = NO;
    NSInteger maxCount = self.selectImageMaxCount - self.selectModels.count;
    if ([self.selectModels containsObject:self.addImageModel]) {
        maxCount = maxCount + 1;
    }
    
    [self.selectFile selectImageInController:self maxCount:maxCount complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets) {
        for (UIImage *image in photos) {
            [self.selectModels insertObject:[HJSelectImageModel modelWithBlock:^(HJSelectImageModel * _Nonnull model) {
                model.image = image;
            }] atIndex:0];
        }
        
        if ([self.selectModels containsObject:self.addImageModel] && self.selectModels.count == self.selectImageMaxCount + 1) {
            [self.selectModels removeObject:self.addImageModel];
        }
        
        execute(^{
            [self.collectionView reloadData];
        }, ^{
            if (self.segmentedControl.selectedSegmentIndex == 0) {
                self.doneButton.enabled = !isEmptyString(self.postTextView.text) || [self isSelectMedia];;
            } else {
                self.doneButton.enabled = !isEmptyString(self.longTextView.text) || [self isSelectMedia];;
            }
            
            NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:self.selectModels.count - 1 inSection:0];
            [self.collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        });
    }];
    
}

- (void)selectVideo {
    self.isSelectVideo = YES;
    [self.selectFile selectVideoInController:self complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets) {
        NSLog(@"assets = %@", assets);
        NSLog(@"photos = %@", photos);
        
        for (int i = 0; i < photos.count; i++) {
            [self.selectModels insertObject:[HJSelectImageModel modelWithBlock:^(HJSelectImageModel * _Nonnull model) {
                model.image = photos[i];
                model.asset = assets[i];
            }] atIndex:0];
        }
        
        if ([self.selectModels containsObject:self.addImageModel] && self.selectModels.count == self.selectVideoMaxCount + 1) {
            [self.selectModels removeObject:self.addImageModel];
        }
        
        execute(^{
            [self.collectionView reloadData];
        }, ^{
            if (self.segmentedControl.selectedSegmentIndex == 0) {
                self.doneButton.enabled = !isEmptyString(self.postTextView.text) || [self isSelectMedia];;
            } else {
                self.doneButton.enabled = !isEmptyString(self.longTextView.text) || [self isSelectMedia];;
            }
            NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:self.selectModels.count - 1 inSection:0];
            [self.collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        });
    }];
    
}


- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *flowLayout= [[UICollectionViewFlowLayout alloc]init];
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _flowLayout = flowLayout;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, leftRightMargin, 0, leftRightMargin);
        CGFloat itemSizeW = HZoom(116);
        flowLayout.itemSize = CGSizeMake(itemSizeW, itemSizeW);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:HJPostInformationSelectImageCell.class forCellWithReuseIdentifier:@"HJPostInformationSelectImageCell"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceHorizontal = YES;
        
    }
    return _collectionView;
}

- (HJSelectFile *)selectFile {
    if (!_selectFile) {
        _selectFile = [[HJSelectFile alloc] init];;
    }
    return _selectFile;
}

- (NSMutableArray *)selectModels {
    if (!_selectModels) {
        _selectModels = [NSMutableArray array];
    }
    return _selectModels;
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
